package myJs.user

import myJs.Utils.{g, _}
import myJs.myPkg.jquery._
import myJs.myPkg.{ColumnOptions, Select2Options, Swal, SwalOptions, TableOptions, TypeaheadOptions}
import org.scalajs.dom.ext.Ajax

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.myPkg.bootstrap.Bootstrap.default._
import org.scalajs.dom.{Element, Event, window}
import scalatags.Text.all._
import myJs.Implicits._
import myJs.tool.Tool
import shared.VarTool


/**
 * Created by yz on 11/5/2020
 */
@JSExportTopLevel("DataSearch")
object DataSearch {

  val tableId = "table"
  val headerMap = VarTool.headerMap
  val fieldNames = VarTool.totalFieldNames


  @JSExport("init")
  def init = {
    initTable
    refreshTableView

    refreshSelect2("barcode").zip(refreshSelect2("sampleName")).
      zip(refreshSelect2("refGene"))

    $("a[data-toggle='tab']").on("shown.bs.tab", (y: Element, e: Event) => {
      $("#result").hide()
    })

  }

  def refreshTableView = {
    val names = fieldNames
    val nameMap = names.map { x =>
      (x -> headerMap.getOrElse(x, x))
    }
    val html = nameMap.map { case (field, name) =>
      label(marginRight := 15,
        input(`type` := "checkbox", checked, value := field, onclick := s"Utils.setColumns('${field}','${tableId}')", name)
      )
    }.mkString
    $("#checkbox").html(html)
    val hideColumns = names.filterNot { x =>
      (headerMap.keyList ::: List("ExonicFunc.refGene", "aaChangeRefGene")).contains(x)
    }
    hideColumns.foreach { x =>
      $("#table").bootstrapTable("hideColumn", x)
      $(s"input:checkbox[value='${x}']").attr("checked", false)
    }
  }


  def initTable = {
    val table = tableId
    val columnNames = fieldNames
    val columns = columnNames.map { columnName =>
      val title = headerMap.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt)
    }
    val options = TableOptions.columns(columns.toJSArray)
    $(s"#${tableId}").bootstrapTable(options)
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case "barcode" => {
      val detailUrl = g.jsRoutes.controllers.userC.DataController.detailInfoBefore().url.toString
      a(title := "详情", href := s"${detailUrl}?barcode=${row("barcode")}", cursor.pointer, target := "_blank",
        v.toString
      ).render
    }
    case _ => v
  }

  def bindEvt = {

  }

  def refreshSelect2(inputName: String) = {
    val url = g.jsRoutes.controllers.userC.DataController.getSingleColumnAll().url.toString
    Ajax.get(url = s"${url}?columnName=${inputName}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS
      val array = data.map { geneType =>
        js.Dictionary("text" -> geneType, "id" -> geneType)
      }
      val options = Select2Options.dictData(array)
      Tool.getInputByName(inputName).select2(options)
    }
  }

  @JSExport("barcodeSearch")
  def barcodeSearch = {
    val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
    val url = g.jsRoutes.controllers.userC.DataController.getAllDataByBarCode().url.toString
    val barcode = Tool.getInputByName("barcode").`val`().toString
    Ajax.get(url = s"${url}?barcode=${barcode}").map { xhr =>
      val rs = xhr.responseText.toJArJDS
      $(s"#${tableId}").bootstrapTable("load", rs)
      $("#result").show()
      layer.close(index)
    }
  }

  @JSExport("sampleNameSearch")
  def sampleNameSearch = {
    val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
    val url = g.jsRoutes.controllers.userC.DataController.getAllDataBySampleName().url.toString
    val sampleName = Tool.getInputByName("sampleName").`val`().toString
    Ajax.get(url = s"${url}?sampleName=${sampleName}").map { xhr =>
      val rs = xhr.responseText.toJArJDS
      $(s"#${tableId}").bootstrapTable("load", rs)
      $("#result").show()
      layer.close(index)
    }
  }

  @JSExport("refGeneSearch")
  def refGeneSearch = {
    val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
    val url = g.jsRoutes.controllers.userC.DataController.getAllDataByRefGene().url.toString
    val refGene = Tool.getInputByName("refGene").`val`().toString
    Ajax.get(url = s"${url}?refGene=${refGene}").map { xhr =>
      val rs = xhr.responseText.toJArJDS
      $(s"#${tableId}").bootstrapTable("load", rs)
      $("#result").show()
      layer.close(index)
    }
  }

}
